package com.sq.partner.manager.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;

/**
 * 请求集中收款平台收款状态查询接口
 * 
 * @author zhouxiuxiu
 *
 */
public class HttpConnectorNewpayUtil {
    private static Logger logger = LogUtil
            .getLog(HttpConnectorNewpayUtil.class);

    /**
     * 请求集中收款平台收款状态查询接口
     * 
     * @param requestUrl
     * @param requestXml
     * @return
     */
    public static String interaction(String requestUrl, String requestXml)
            throws Exception {
        String responseXml = "";
        OutputStream output = null;
        try {
            HttpURLConnection http = null;
            URL url = new URL(requestUrl);
            http = (HttpURLConnection) url.openConnection();
            // 设置连接参数
            http.setRequestMethod("POST");
            http.setRequestProperty("content-type", "text/html");
            http.setUseCaches(false);
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            output = http.getOutputStream();
            output.write(requestXml.getBytes("UTF-8"), 0,
                    requestXml.getBytes("UTF-8").length);
            output.flush();
            StringBuffer bf = new StringBuffer();
            InputStream stream = http.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    stream, "utf-8"));
            String line = "";
            while ((line = reader.readLine()) != null) {
                bf.append(line);
            }
            if (bf.length() > 0) {
                responseXml = bf.toString();
            }

        } catch (Exception e) {
            logger.error(e);
            throw e;
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    logger.error("释放OutputStream失败", e);
                    /*throw e;*/
                }
            }
        }

        return responseXml;
    }
}
